package com.loopj.ohos.http.sample;

import com.loopj.ohos.http.AsyncHttpClient;
import com.loopj.ohos.http.RequestHandle;
import com.loopj.ohos.http.RequestParams;
import com.loopj.ohos.http.ResponseHandlerInterface;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Random;

import com.loopj.ohos.http.ext.LocalHiLog;
import cz.msebera.android.httpclient.Header;
import cz.msebera.android.httpclient.HttpEntity;

/**
 * FilesSample
 */
public class FilesSample extends PostSample {
    /**
     * FilesSample
     */
    public static final String LOG_TAG = "FilesSample";

    @Override
    public int getSampleTitle() {
        return ResourceTable.String_title_post_files;
    }

    @Override
    public boolean isRequestBodyAllowed() {
        return false;
    }

    @Override
    public RequestHandle executeSample(AsyncHttpClient client, String URL, Header[] headers, HttpEntity entity, ResponseHandlerInterface responseHandler) throws IOException {
        try {
            RequestParams params = new RequestParams();
            final String contentType = RequestParams.APPLICATION_OCTET_STREAM;
            params.put("fileOne", createTempFile("fileOne", 1020), contentType, "fileOne");
            params.put("fileTwo", createTempFile("fileTwo", 1030), contentType);
            params.put("fileThree", createTempFile("fileThree", 1040), contentType, "customFileThree");
            params.put("fileFour", createTempFile("fileFour", 1050), contentType);
            params.put("fileFive", createTempFile("fileFive", 1060), contentType, "testingFileFive");
            params.setHttpEntityIsRepeatable(true);
            params.setUseJsonStreamer(false);
            return client.post(this, URL, params, responseHandler);
        } catch (FileNotFoundException fnfException) {
            LocalHiLog.error(LOG_TAG, "executeSample failed with FileNotFoundException", fnfException);
        }
        return null;
    }

    /**
     * createTempFile
     *
     * @param namePart createTempFile
     * @param byteSize createTempFile
     * @return createTempFile
     * @throws IOException string
     */
    public File createTempFile(String namePart, int byteSize) throws IOException {
        FileOutputStream fos = null;
        try {
            File ff = File.createTempFile(namePart, "_handled", getCacheDir());
            fos = new FileOutputStream(ff);
            Random rr = new Random();
            byte[] buffer = new byte[byteSize];
            rr.nextBytes(buffer);
            fos.write(buffer);
            fos.flush();
            fos.close();
            return ff;
        } catch (Throwable tt) {
            LocalHiLog.error(LOG_TAG, "createTempFile failed", tt);
        }finally {
            fos.close();
        }
        return null;
    }
}
